<?php

class Purchase_Model extends Model {

    public function __construct() {
        parent::__construct();
       // echo "purchase_model";
    }

    public function getData() {
        /**@TODO
         *
         * 1. change löschen to lock
         *
         * 2. toggle function
         *
         * 3. detail page to add article
         * */





        $data = array('msg'=>'', 'list'=>null, 'userList'=>array());

        if(isset($_GET['purchaseId']) && !empty($_GET['purchaseId'])){
            $data['purchaseId'] = intval($_GET['purchaseId']);
            $data['count'] = 1;
            if (isset($_POST['action'])) {
                switch (strtolower($_POST['action'])) {

                    case 'add':
                        $data = $this->add($data);
                        break;
                    case 'addpurchasearticle':
                        $data = $this->addPurchaseArticle($data);
                        break;
                    case 'löschen':
                        if(isset($_POST['purchaseArticleId']) && is_array($_POST['purchaseArticleId'])){

                            $this->delPurchaseArticle( $data['purchaseId'], $_POST['purchaseArticleId']);
                        }
                        break;
                    case 'export': //here is dummy to ignore error message
                        break;

                    default:
                        echo "error, unknown action!!";
                }

            }

            $data['view'] = 'detail';
            //$data['purchaseId'] = intval($_GET['purchaseId']);
            $data['listArticle'] = $this->db->select("SELECT * FROM article");

            $sql = "SELECT * FROM article LEFT JOIN purchase_article ON article.id = purchase_article.article_id WHERE purchase_id = :id";

            $sth = $this->db->prepare($sql);

            //echo "3";
            $sth->execute(array(':id' => $data['purchaseId']));
            $einkauflist = $sth->fetchAll();
            //var_dump($einkauflist);
            $data['einkauflist'] = array();
            if (is_array($einkauflist) && count($einkauflist) > 0){
                $data['einkauflist'] = $einkauflist;
            }

            if (isset($_POST['action']) && strtolower($_POST['action']) == 'export') {
               $data = $this->exportCvs($data);
            }

        }else{

            $sth = $this->db->prepare("SELECT * FROM user WHERE name NOT IN ('chen', 'jessica') ");
            //echo "3";
            $sth->execute();
            $data['userList'] = $sth->fetchAll();


            if (isset($_POST['action'])) {
                switch (strtolower($_POST['action'])) {
                    case 'löschen':
                        $this->del();
                        break;
                    case 'einlagern':
                        $this->setStatus(Database::$In);
                        break;
                    case 'auslagern':
                        $this->setStatus(Database::$AUS);
                        break;
                    case 'add':
                        $data = $this->add($data);
                        break;

                    default:
                        echo "error, unknown action!!";
                }

            }

            $data['view'] = 'index';

            $data['list']=$this->getPurchaseList();
            $sql = "SELECT * FROM purchase WHERE `lock`='".Database::$Nein."' ORDER BY create_time DESC";
            try{
                $data['list'] = $this->db->select($sql);
            }catch (PDOException $e){
                echo $e->getMessage();
            }

            $max = $this->db->select("SELECT MAX(id) FROM purchase");
            //var_dump($max);
            if(is_array($max) && count($max)){
                $res = array_values($max[0]);
                $data['nextPurchaseId'] = $res[0]+1;
            }else{
                $data['nextPurchaseId'] = 1;
            }
        }


        return $data;
    }

    protected  function add($data){

        $userId = trim($_POST['user_id']);
        $comment = trim($_POST['comment']);

        $sth = $this->db->prepare("SELECT * FROM user WHERE id = :userId");
        //echo "3";
        $sth->execute(array(':userId' => $userId));
        $userName = '';
        $aUser = $sth->fetchAll();


        if (is_array($aUser) && count($aUser) > 0){
            $userName = $aUser[0]['name'];
        }

        try{

            $dTime = new DateTime();
            $createTime = $dTime->format(Database::$TimeFormat);

            $id = $this->db->insert('purchase', array('create_time'=>$createTime, 'user_id'=>$userName, 'total_price_e'=>0, 'last_change_time'=>$createTime, 'lock'=>Database::$Nein,'comment'=>$comment,'status'=>Database::$AUS));

            $data['msg'] = '<div class="successMsg">'.filter_var($userName, FILTER_SANITIZE_STRING) .' | '.filter_var($createTime, FILTER_SANITIZE_STRING) .' | '.filter_var($comment, FILTER_SANITIZE_STRING) .' wurde angelegt.</div>';
            $data['pur'] = '<div class="successMsg">'.filter_var($userName, FILTER_SANITIZE_STRING) .' | '.filter_var($createTime, FILTER_SANITIZE_STRING) .' | '.filter_var($comment, FILTER_SANITIZE_STRING) .' wurde angelegt.</div>';
        }catch (Exception $e) {
            echo 'Exception: article cannot be inserted: ',  $e->getMessage(), "\n";
        }

        return $data;
    }

    protected  function del(){
        if(isset($_POST['purchaseId']) && is_array($_POST['purchaseId'])){
            $where = "id IN (".implode(' ,', $_POST['purchaseId']).")";
            //echo $where;
            $dTime = new DateTime();
            $lockTime = $dTime->format(Database::$TimeFormat);
            $this->db->update('purchase', array('lock'=>Database::$JA, 'lock_time'=>$lockTime),$where);
            $this->updateCurrentStock();
        }

    }

    protected  function getPurchaseList(){
        $list = array();
        $sql = "SELECT * FROM purchase WHERE `lock`='".Database::$Nein."' ORDER BY create_time DESC";
        try{
            $list = $this->db->select($sql);
        }catch (PDOException $e){
            echo $e->getMessage();
        }
        return $list;

    }

    protected  function setStatus($status){
        if(isset($_POST['purchaseId']) && is_array($_POST['purchaseId'])){
            $where = "id IN (".implode(' ,', $_POST['purchaseId']).")";
            $dateTime  = null;

            $dTime = new DateTime();
            $dateTime = $dTime->format(Database::$TimeFormat);

            $this->db->update('purchase', array('status'=>$status, "last_change_time"=>$dateTime), $where);
            $this->updateCurrentStock();
        }


    }

    protected  function delPurchaseArticle($purchaseId, $purchaseArticleIds){
            //var_dump($_POST);
        //get total price of removing article

        $idList = " WHERE `id` IN (".implode(' ,', $purchaseArticleIds).")";
        $sql = "SELECT  SUM( total_price_e ) AS totalprice FROM `purchase_article`".$idList;
        /** @var $sth PDOStatmen */
        echo $sql;
        $sth = $this->db->select($sql);
        if (count($sth) > 0){
            $diffPrice = round($sth[0]['totalprice'], 2);
            //var_dump($sth);
            $this->updateTotalPrice($purchaseId, $diffPrice*(-1));

            $where = "id IN (".implode(' ,', $purchaseArticleIds).")";

            //echo $where;
            $this->db->delete('purchase_article', $where, 50);
        }else{
            throw new Exception('Error, the ids can not be found in purchase_article!');
        }


    }


//article_id, supplier,count,price_e
    protected  function addPurchaseArticle($data){
        $bAllowWrite = true;
        $data['ean'] = '';
        $data['count'] = 1;
        if (isset($data['count']) && !empty($_POST['count'])){
            $data['count'] = intval($_POST['count']);
        }

        if (isset($_POST['ean']) && !empty($_POST['ean'])){
            $ean = filter_var(trim($_POST['ean']), FILTER_SANITIZE_STRING);
            $sth = $this->db->prepare("SELECT * FROM article WHERE ean = :ean");
            //echo "3";
            $sth->execute(array(':ean' => $ean));
            $article = $sth->fetch();
            if ($sth->rowCount() > 0){
                $data['ean'] =$ean;
                $data['article_id'] = $article['id'];
                $data['article_name'] = $article['name_de'];

                $postSet = array('supplier', 'price_e', 'count');
                foreach ($postSet As $postData){
                    if (isset($_POST[$postData]) && !empty($_POST[$postData])){
                        $data[$postData] = $_POST[$postData];
                    }else{
                        $data[$postData]  = '';
                        if($postData != 'supplier')
                            $bAllowWrite = false;
                    }
                }

            }
             else{

                $data['msg'] = '<div class="errorMsg"> Diese EAN Nr. '.$ean.' ist unbekannt! Bitte zuerst anlegen, dann versuchen Sie noch mal.</div>';

                $bAllowWrite = false;
                $postSet = array('article_id', 'supplier', 'price_e', 'count');
                foreach ($postSet As $postData){
                    if (isset($_POST[$postData]) && !empty($_POST[$postData])){
                        $data[$postData] = $_POST[$postData];
                    }else{
                        $data[$postData]  = '';
                    }
                }

            }
        }else{
            $postSet = array('article_id', 'supplier', 'price_e', 'count');
            foreach ($postSet As $postData){
                if (isset($_POST[$postData]) && !empty($_POST[$postData])){
                    $data[$postData] = $_POST[$postData];
                }else{
                    $data[$postData]  = '';
                    if($postData != 'supplier')
                        $bAllowWrite = false;
                }
            }

        }
        if ($bAllowWrite){
            //get article name, here is just for rend msg info
            $sth = $this->db->prepare("SELECT * FROM article WHERE id = :id");
            //echo "3";
            $sth->execute(array(':id' => $data['article_id']));
            $textArticle = $sth->fetch();
            if ($sth->rowCount() > 0){
                //echo "4";
            }
            //echo "=====";
            //var_dump($textArticle);

            //if there is already a same article then update
            //$sth = $this->db->prepare("SELECT * FROM purchase_article WHERE article_id = :articleId");
            //$sth->execute(array(':articleId' => $data['article_id']));
            //$existArticle = $sth->fetchAll();
            //if ($sth->rowCount() > 0){
            //    $where = 'article_id='.$data['article_id'];
            //    $existArticle
            //    $this->db->update('purchase_article', array(),);
            //}else{
            //}

            $total = $data['count'] * $data['price_e'];

            //echo "==========";
            //var_dump($data['count'] * $data['price_e']);
            $id = $this->db->insert('purchase_article', array('purchase_id'=>$data['purchaseId'], 'article_id'=>$data['article_id'], 'price_e'=>$data['price_e'], 'count'=>$data['count'], 'total_price_e'=>$total,'supplier'=>$data['supplier']));



            $data['msg'] = '<div class="successMsg">'.$textArticle['name_de'] .': '.$data['price_e'].' X '.$data['count'].' = '.$total. '  EURO</div>';
            //nach der speichern reset daten
            $postSet = array('article_id', 'supplier', 'price_e', 'count', 'ean');
            foreach ($postSet As $postData){
                $data[$postData]  = '';
            }

            //update purchase.total_price_e
            $this->updateTotalPrice($data['purchaseId'], $total);

        }


        return $data;

    }

    protected function updateTotalPrice($id, $price){
        //if (is_array($id) && count($id)>0){
        $sth = $this->db->prepare("SELECT * FROM purchase WHERE id = :id");
        //echo "3";
        $sth->execute(array(':id' => $id));
        $res = $sth->fetchAll();
        //var_dump($res);
        if ($sth->rowCount() > 0){

            $currentPrice = $price+$res[0]['total_price_e'];
            /*echo "currentPrice:".$currentPrice;
            echo "--price:".$price;
            echo "--alter:".$res[0]['total_price_e'];*/
            if ( $currentPrice >=  0){
                $this->db->update('purchase', array('total_price_e'=>$currentPrice), "`id`='".$id."'");
            }else{
                throw new Exception("Error, total price is already 0!!");
            }
        }

    }

    protected function exportCvs($data, $tpl ='', $content =''){

        $content = '';
        $content .= implode( Database::$cvsDelimiter, array_keys( Database::$purchaseArticleSet ) );
        $content .= "\n";
        $list = $data['einkauflist'];
        $fieldSet = array_values( Database::$purchaseArticleSet );

        foreach ( $list AS $item ) {
            $cnt = 1;
            foreach ( $fieldSet AS $field ) {
                $delimiter = Database::$cvsDelimiter;
                if ($cnt == count($fieldSet)){
                    $delimiter = "\n";
                }
                $content .=  $item[$field].$delimiter;
                $cnt++;
            }
        }

        $data['view'] = 'export';
        Helper::download_send_headers('views/purchase/export_tpl.php', $content, "einkauf");
        return $data;
    }




}